//
//  UIWebControlIOSView.m
//  UIWebViewTest
//
//  Created by yewei on 13-6-13.
//  Copyright (c) 2013年 yewei. All rights reserved.
//

#import "UIWebControl.h"
#import "CustomLoadingView.h"
#import "Common.h"
#import "TransforController.h"
#import "BottomBarViewController.h"
#import "SportsDetailViewController.h"
#import "GoodDetailViewController.h"
#import "CommonCellViewController.h"
#import "MovieViewController.h"

@interface WebIOS ()
@property CGRect frame;
@property (nonatomic,retain) UIWebView *web;
@property (nonatomic, strong)UIView *view_screen;
@property (nonatomic,retain) NSURL *webUrl;
@property BOOL shoudRotate;
@end

@implementation WebIOS
@synthesize web;
@synthesize frame;
@synthesize webUrl;
@synthesize delegate;
@synthesize scalesPageToFit;
@synthesize shoudRotate;

-(id)initWithFrame:(CGRect)f url:(NSURL *)url
{
    self.frame = f;
    self = [super init];
    if (self)
    {
        self.webUrl = url;
        scalesPageToFit = NO;
        self.shoudRotate = NO;
        // Custom initialization
    }
    return self;
}

-(void)loadView
{
    self.view = [[UIView alloc]init];
    self.view_screen = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    self.view_screen.backgroundColor = [UIColor whiteColor];
    self.web = [[UIWebView alloc]init];
    self.web.delegate = self;
    self.web.allowsInlineMediaPlayback = YES;
    self.web.scalesPageToFit = NO;
    self.view = self.view_screen;
    [self.view addSubview:self.web];

}

-(void)dealloc
{
    [webUrl release];
    [web release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    if([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        [self setEdgesForExtendedLayout:UIRectEdgeLeft | UIRectEdgeRight];
    }
#endif
	// Do any additional setup after loading the view.
   
    [self.view setFrame:[UIScreen mainScreen].bounds];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:self.webUrl];
    [self.web loadRequest:request];
    self.web.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.web.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    self.web.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
   [self.web stringByEvaluatingJavaScriptFromString:@"document. body.style.zoom = 0.5;"];
    [self.web setScalesPageToFit:scalesPageToFit];
    [request release];
    [[CustomLoadingView shareInstance] showLoadingViewWithSuperView:self.view message:@"测试啦..."];
    [[CustomLoadingView shareInstance] setRectHidden:YES];
    [[CustomLoadingView shareInstance] setWillCoverTouchEvent:NO];
    
    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:-65 andTitle:self.string_title];
    [self.view addSubview:view_navigationBar];
    NSLog(@"%s || target_id:%d and type:%@", __FUNCTION__, self.target_id, self.type);
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)initToolbar{
    BottomBarViewController *bottomBarController = [[BottomBarViewController alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - HEIGHT_BOTTOM_BAR, 320, 45)];
    bottomBarController.bottomBarNavigationController = self.navigationController;
    NSDictionary *dic_temp = [NSDictionary dictionaryWithObjectsAndKeys:self.type ,@"type", [NSNumber numberWithInt:self.target_id], @"id",[NSString stringWithFormat:@"%@",self.webUrl],@"url", nil];
    [bottomBarController setEnabledWithData:dic_temp];
    [self.view_screen addSubview:bottomBarController.view];
}

#pragma mark uiwebView delegate
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    if(self.delegate && [self.delegate respondsToSelector:@selector(webView:shouldLoadWithRequest:navigationType:)])
//    {
//        return [self.delegate webView:webView shouldLoadWithRequest:request navigationType:navigationType];
//    }
////    NSURL *requestURL =[ [ request URL ] retain ];
////    NSLog(@"request url = %@",[requestURL absoluteString] );
////    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [[requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ]isEqualToString: @"mailto" ])
////        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) )
////    {
////        
////       // return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease] ];
////        [ requestURL release ];
////        return NO;
////    }
////    [ requestURL release ];
//    return YES;
//}
#pragma mark UIWebViewDelegate方法
/**
 *开始加重请求拦截
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSString *urlstr = request.URL.absoluteString;
    NSRange range = [urlstr rangeOfString:@"key="];
    NSRange typeRange = [urlstr rangeOfString:@"type="];
    if (range.length!=0) {
        NSString *method = [urlstr substringFromIndex:(range.location+range.length)];
//        method = urlstr;
        SEL selctor = NSSelectorFromString(method);
        [self performSelector:selctor withObject:nil];
    }
    if (typeRange.length != 0) {
        if ([urlstr rangeOfString:@"GOODS"].length != 0) {
            NSString *ref_id = [urlstr componentsSeparatedByString:@"id="][1];
            [self jump:@"GOODS" ref_id:ref_id url:nil name:nil];
            return NO;
        } else if ([urlstr rangeOfString:@"STORE"].length != 0) {
            NSString *ref_id = [urlstr componentsSeparatedByString:@"id="][1];
            [self jump:@"STORE" ref_id:ref_id url:nil name:nil];
            return NO;
        } else if ([urlstr rangeOfString:@"LIST"].length != 0) {
            NSString *api = nil;
            NSString *name = nil;
            if ([urlstr rangeOfString:@"name="].length != 0) {
                NSString *api_name = [urlstr componentsSeparatedByString:@"api="][1];
                api = [api_name componentsSeparatedByString:@"&name="][0];
                name = [api_name componentsSeparatedByString:@"&name="][1];
            } else {
                api = [urlstr componentsSeparatedByString:@"api="][1];
            }
            
            [self jump:@"LIST" ref_id:nil url:api name:name];
            return NO;
        }
    }
    return YES;
}

//首页跳转
- (void)jump:(NSString*)type ref_id:(NSString*)ref_id url:(NSString*)url name:(NSString*)name
{
    if ([type isEqualToString:@"STORE"]) {
        SportsDetailViewController *storeDetailCtrl = [[SportsDetailViewController alloc] init];
        storeDetailCtrl.target_id = [ref_id intValue];
        storeDetailCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:storeDetailCtrl animated:YES];
        
    } else if ([type isEqualToString:@"GOODS"]) {
        GoodDetailViewController *goodDetailCtrl = [[GoodDetailViewController alloc] init];
        //            GoodDetailViewController *goodDetailCtrl = [[GoodDetailViewController alloc]initWithFrame:self.view.frame style:UITableViewStylePlain navigationBarHeight:0];
        goodDetailCtrl.goodId = [ref_id intValue];
        goodDetailCtrl.hidesBottomBarWhenPushed = YES;
        //            UIView *navView = [TransforController shardeInstanceOfNavigationBarCoverViewWithY:0];
        //            [goodDetailCtrl.view addSubview:navView];
        //            [goodDetailCtrl.tableView.superview addSubview:navView];
        //            [goodDetailCtrl.tableView setFrame:CGRectMake(0, 45, 320, 523)];
        [goodDetailCtrl.view setFrame:self.view.bounds];
        //            [goodDetailCtrl.view insertSubview:navView aboveSubview:goodDetailCtrl.tableView];
        [self.navigationController pushViewController:goodDetailCtrl animated:YES];
        
    } else if ([type isEqualToString:@"LIST"]) {
        NSArray *api_req = [url componentsSeparatedByString:@"/"];
        if (api_req.count >1) {
            CommonCellViewController *commonCellCtrl = [[CommonCellViewController alloc] init];
            commonCellCtrl.isDisplayTopMenu = false;
            commonCellCtrl.title = name;
            commonCellCtrl.is_load_more = @"NO";
            commonCellCtrl.API_REQ = [NSArray arrayWithArray:api_req];
            commonCellCtrl.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commonCellCtrl animated:YES];
        }
    } else if ([type isEqualToString:@"MOVIE"]) {
        MovieViewController *listViewCtrl = [[MovieViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
        listViewCtrl.type = 8;
        listViewCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:listViewCtrl animated:YES];
    }
    
}

/**
 *  OC执行JS代码
 */

-(void)openMyAlbum
{
    UIImagePickerController *vc = [[UIImagePickerController alloc]init];
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)openMyCamera
{
    UIImagePickerController *vc = [[UIImagePickerController alloc]init];
    vc.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webView did start load");
    self.shoudRotate = NO;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"webView did finish load");
    [[CustomLoadingView shareInstance] stopLoadingView];
    if(self.delegate && [self.delegate respondsToSelector:@selector(didFinishLoadWeb)])
    {
        [self.delegate didFinishLoadWeb];
    }
    if([self.type isEqualToString:@"STORE"] || [self.type isEqualToString:@"GOODS"] || [self.type isEqualToString:@"TOPIC"] || [self.type isEqualToString:@"NEWS"] || [self.type isEqualToString:@"STRATEGY"] || [self.type isEqualToString:@"URL"]){
        [self initToolbar];
        [self.web setFrame:CGRectMake(0, 0, 320, self.view.frame.size.height - HEIGHT_BOTTOM_BAR)];
//        self.view.frame = CGRectMake(0, 65, 320, 460);
    }else{
        [self.web setFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
//        self.view.frame = CGRectMake(0, 65, 320, 568);
    }
    self.shoudRotate = YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if([error code] == NSURLErrorCancelled)
    {
        return;
    }
    NSLog(@"webView did fail load,ERROR:%@",[error localizedDescription]);
    [[CustomLoadingView shareInstance] stopLoadingView];
    if(self.delegate && [self.delegate respondsToSelector:@selector(didFailLoadWebWithErrorMessage:)])
    {
        [self.delegate didFailLoadWebWithErrorMessage:[error localizedDescription]];
    }
    else
    {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"Web did fail load", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Confirm", nil) otherButtonTitles:nil];
//        [alert show];
//        [alert release];
    }
    
   
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return self.shoudRotate;
}

// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
- (NSUInteger) supportedInterfaceOrientations{
#ifdef __IPHONE_6_0
    // return UIInterfaceOrientationMaskAllButUpsideDown;
    return UIInterfaceOrientationMaskAll;
#endif
}

- (BOOL) shouldAutorotate {
    return self.shoudRotate;
}

@end